package Code;

import java.util.List;

public class Code206 {
    static class ListNode {
        int val;
        ListNode next;
        ListNode(int val) {
            this.val = val;
        }
    }
    static ListNode reverse(ListNode head){
        ListNode pre = null;
        ListNode p =head;
        while(p != null){
            ListNode node = p.next;
            p.next = pre;
            pre = p;
            p =node;
        }
        return pre;
    }
    static ListNode reverse1(ListNode head){
        if(head == null || head.next == null){
            return head;
        }
        ListNode newHead = reverse1(head.next);
        head.next.next = head;// 将当前节点插入到反转后的链表的尾部
        head.next = null;
        return newHead;
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(3);


//        ListNode reversedHead = reverse(head);
        ListNode reversedHead = reverse1(head);
        // 打印反转后的链表
        ListNode current = reversedHead;
        while (current != null) {
            System.out.print(current.val + " ");
            current = current.next;
        }
    }
}
